<script setup>
import {SearchOutlined} from "@ant-design/icons-vue";
import {onMounted, ref} from "vue";
import {queryUserStatistics} from "@/api/statistics.js";
import * as echarts from "echarts";

const dateForm = ref({
  startDate: '',
  endDate: ''
})
const searchTime = ref()
const dates = ref([])
const newUsers = ref([])
const totalUsers = ref([])

const formatDateToBeijingISO = (date) => {
  const beijingOffset = 8 * 60; // 北京时间相对于UTC的分钟数
  const utcDate = new Date(date.getTime() + (beijingOffset * 60 * 1000));
  return `${utcDate.toISOString().split('T')[0]}T00:00:00`;
}

const onClickWeekUser = () => {
  const today = new Date()
  const startOfWeek = new Date(today)
  startOfWeek.setDate(today.getDate() - 6) // 向前推7天
  const endOfWeek = today

  dateForm.value.startDate = formatDateToBeijingISO(startOfWeek)
  dateForm.value.endDate = formatDateToBeijingISO(endOfWeek)
  fetchUserStatistics()
}

const onClickMouthUser = () => {
  const today = new Date()
  const startOfMonth = new Date(today)
  startOfMonth.setDate(today.getDate() - 29) // 向前推30天
  const endOfMonth = today

  dateForm.value.startDate = formatDateToBeijingISO(startOfMonth)
  dateForm.value.endDate = formatDateToBeijingISO(endOfMonth)
  fetchUserStatistics()
}

const onClickSearchTime = () => {
  if (!searchTime.value || !searchTime.value[0] || !searchTime.value[1]) {
    return
  }
  dateForm.value.startDate = formatDateToBeijingISO(searchTime.value[0].$d)
  dateForm.value.endDate = formatDateToBeijingISO(searchTime.value[1].$d)
  fetchUserStatistics()
}

const fetchUserStatistics = () => {
  queryUserStatistics(dateForm.value)
    .then(res => {
      dates.value = res.data.data.dateList
      newUsers.value = res.data.data.newUserNum
      totalUsers.value = res.data.data.userNum
      initChart() // 初始化图表
    })
    .catch(error => {
      console.log(error)
    })
}

// 初始化图表
const initChart = () => {
  const chartDom = document.getElementById('userStatistics')
  const myChart = echarts.init(chartDom)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    legend: {
      data: ['新增用户', '用户总数']
    },
    xAxis: {
      type: 'category',
      data: dates.value, // 使用响应式数据
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '新增用户',
        min: 0,
        alignTicks: true
      },
      {
        type: 'value',
        name: '用户总数',
        min: 0,
        alignTicks: true
      }
    ],
    series: [
      {
        name: '新增用户',
        type: 'bar',
        data: newUsers.value, // 使用响应式数据
        color: '#ff792f'
      },
      {
        name: '用户总数',
        type: 'line',
        yAxisIndex: 1,
        data: totalUsers.value, // 使用响应式数据
        color: '#1f77ff'
      }
    ]
  }

  option && myChart.setOption(option)

  // 监听窗口大小变化，重绘图表
  window.addEventListener('resize', () => {
    myChart.resize()
  })
}

// 组件挂载时默认获取数据
onMounted(() => {
  onClickMouthUser() // 可以设置为默认显示本月数据
})
</script>

<template>
  <div class="user-statistics-container">
    <div class="button-container">
      <a-button type="primary" @click="onClickWeekUser">近一周</a-button>
      <a-button type="primary" @click="onClickMouthUser">近一月</a-button>
      <a-range-picker v-model:value="searchTime" :format="'YYYY-MM-DD'"/>
      <a-button type="primary" shape="circle" @click="onClickSearchTime">
        <template #icon>
          <SearchOutlined/>
        </template>
      </a-button>
    </div>
    <div id="userStatistics" class="user-statistics"></div>
  </div>
</template>

<style scoped>
.user-statistics-container .button-container {
  display: flex;
  justify-content: right;
  gap: 10px;
}

.user-statistics {
  margin-top: 10px;
  width: 100%;
  height: 400px;
}
</style>
